import requests
from django.shortcuts import render
from matplotlib.pyplot import cla
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework_simplejwt.tokens import RefreshToken
from django.contrib.auth import authenticate
from .serializers import *
from rest_framework.permissions import IsAuthenticated
from django.contrib.auth import get_user_model
from django.core.paginator import Paginator
from rest_framework import viewsets
from rest_framework.decorators import action
from .models import TodoList
from utils.pagination import MyPageNumberPagination
import os
from django.conf import settings
User = get_user_model()

# Create your views here.


class LoginView(APIView):
    permission_classes = []  # 登录接口不需要认证
    
    def post(self, request):
        username = request.data.get('username')
        password = request.data.get('password')
        
        if not username or not password:
            return Response({
                'code': 400,
                'message': '用户名和密码不能为空'
            }, status=status.HTTP_400_BAD_REQUEST)
            
        user = authenticate(username=username, password=password)
        
        if user:
            # 生成 token
            refresh = RefreshToken.for_user(user)
            
            # 获取用户信息
            serializer = UserSerializer(user)
            user_data = serializer.data
            
            # 统一返回格式
            return Response({
                'code': 200,
                'message': '登录成功',
                'data': {
                    'token': str(refresh.access_token),
                    'refresh': str(refresh),
                    'user': {
                        'id': user.id,
                        'username': user.username,
                        'is_superuser': user.is_superuser,
                        'email': user.email,
                        'last_login': user.last_login,
                        'date_joined': user.date_joined
                    }
                }
            })
        else:
            return Response({
                'code': 401,
                'message': '用户名或密码错误'
            }, status=status.HTTP_401_UNAUTHORIZED)


class LogoutView(APIView):
    permission_classes = [IsAuthenticated]  # 需要认证才能访问
    
    def post(self, request):
        try:
            # 获取refresh token
            refresh_token = request.data.get('refresh')
            if refresh_token:
                # 将refresh token加入黑名单
                token = RefreshToken(refresh_token)
                token.blacklist()
            
            return Response({'code': 200,'message': '退出成功'})
        except Exception as e:
            return Response({'code': 400,'message': '退出失败'})


class UserViewSet(viewsets.ModelViewSet):
    """
    用户管理视图集
    提供用户的CRUD操作
    """
    queryset = User.objects.all()
    serializer_class = UserSerializer
    permission_classes = [IsAuthenticated]
    pagination_class = MyPageNumberPagination
    
    @action(detail=False, methods=['get'], url_path='avatar')
    def get_avatar(self, request):
        """获取当前用户头像"""
        user = request.user
        avatar_url = 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif'
        
        # 如果用户有自定义头像，使用自定义头像
        if hasattr(user, 'avatar') and user.avatar:
            avatar_url = request.build_absolute_uri(user.avatar.url)
            
        return Response({
            'code': 200,
            'message': '获取成功',
            'data': {
                'avatar': avatar_url,
                'username': user.username,
                'id': user.id
            }
        })
    
    @action(detail=True, methods=['post'], url_path='upload-avatar')
    def upload_avatar(self, request, pk=None):
        """上传用户头像"""
        try:
            user = self.get_object()
            # 合并POST数据和文件数据
            data = request.data.copy()
            data.update(request.FILES)
            serializer = AvatarUploadSerializer(data=data)
            
            if not serializer.is_valid():
                return Response({'code': 400,'message': '头像上传失败','errors': serializer.errors}, status=status.HTTP_400_BAD_REQUEST)
            
            avatar_file = serializer.validated_data['avatar']
            
            # 删除旧头像文件
            if user.avatar and user.avatar.name:
                old_avatar_path = os.path.join(settings.MEDIA_ROOT, user.avatar.name)
                if os.path.exists(old_avatar_path):
                    try:
                        os.remove(old_avatar_path)
                    except OSError:
                        pass  # 忽略删除失败的情况
            
            # 保存新头像
            user.avatar = avatar_file
            user.save()
            
            # 构建头像URL
            avatar_url = request.build_absolute_uri(user.avatar.url)
            
            # 调试信息
            print(f"DEBUG: 上传成功，头像URL = {avatar_url}")
            print(f"DEBUG: user.avatar.url = {user.avatar.url}")
            print(f"DEBUG: request.get_host() = {request.get_host()}")
            
            return Response({'code': 200,'message': '头像上传成功','data': {'avatar': avatar_url,'user_id': user.id,'username': user.username}}, status=status.HTTP_200_OK)
        except Exception as e:
            return Response({'code': 500,'message': f'头像上传失败: {str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
    
    def list(self, request, *args, **kwargs):
        """获取用户列表"""
        try:
            # 获取查询参数
            keyword = request.GET.get('keyword', '')
            
            # 构建查询条件
            queryset = self.get_queryset()
            
            # 关键词搜索
            if keyword:
                queryset = queryset.filter(username__icontains=keyword)
            
            # 使用DRF默认分页
            page = self.paginate_queryset(queryset)
            if page is not None:
                serializer = self.get_serializer(page, many=True, context={'request': request})
                # 获取分页信息
                paginated_response = self.get_paginated_response(serializer.data)
                
                # 重新构造响应格式以匹配前端期望
                return Response({
                    'code': 200,
                    'message': '获取成功',
                    'data': {
                        'results': serializer.data,
                        'count': paginated_response.data['count']
                    }
                })
            
            # 如果没有分页，返回所有数据
            serializer = self.get_serializer(queryset, many=True, context={'request': request})
            return Response({
                'code': 200,
                'message': '获取成功',
                'data': {
                    'results': serializer.data,
                    'count': queryset.count()
                }
            })
            
        except Exception as e:
            return Response({'code': 400,'message': f'获取用户列表失败: {str(e)}'}, status=status.HTTP_400_BAD_REQUEST)
    
    def create(self, request, *args, **kwargs):
        """创建用户"""
        serializer = UserCreateSerializer(data=request.data)
        if serializer.is_valid():
            user = serializer.save()
            return Response({'code': 200,'message': '创建成功','data': UserSerializer(user).data})
        return Response({'code': 400,'message': '创建失败','data': serializer.errors}, status=status.HTTP_400_BAD_REQUEST)
    
    def update(self, request, *args, **kwargs):
        """更新用户"""
        # print(f"DEBUG update: kwargs = {kwargs}")
        # print(f"DEBUG update: self.kwargs = {self.kwargs}")
        # print(f"DEBUG update: URL中的pk = {kwargs.get('pk') or self.kwargs.get('pk')}")
        instance = self.get_object()
        serializer = UserUpdateSerializer(instance, data=request.data, partial=False)
        
        if serializer.is_valid():
            updated_user = serializer.save()
            return Response({'code': 200,'message': '更新成功','data': UserSerializer(updated_user).data})
        return Response({'code': 400,'message': '更新失败','data': serializer.errors}, status=status.HTTP_400_BAD_REQUEST)
    
    def destroy(self, request, *args, **kwargs):
        """删除用户"""
        try:
            instance = self.get_object()
            
            # 检查是否为超级管理员
            if instance.is_superuser:
                return Response({'code': 400,'message': '不能删除超级管理员用户'}, status=status.HTTP_400_BAD_REQUEST)
            
            instance.delete()
            return Response({'code': 200,'message': '删除成功'})
        except Exception as e:
            return Response({'code': 400,'message': f'删除失败: {str(e)}'}, status=status.HTTP_400_BAD_REQUEST)


class TodoListViewSet(viewsets.ModelViewSet):
    queryset = TodoList.objects.all()
    serializer_class = TodoListSerializer
    permission_classes = [IsAuthenticated]
    pagination_class = MyPageNumberPagination

    @action(detail=False, methods=['post'], url_path='create_todo')
    def create_todo(self, request):
        try:
            text = request.data.get('text')
            if not text:
                return Response({
                    'code': 400,
                    'message': '文本内容不能为空'
                }, status=status.HTTP_400_BAD_REQUEST)

            todo = TodoList.objects.create(
                description=text,
                created_by=request.user
            )

            serializer = self.get_serializer(todo)
            return Response({
                'code': 200,
                'message': '创建成功',
                'data': serializer.data
            })
        except Exception as e:
            return Response({
                'code': 500,
                'message': f'创建失败: {str(e)}'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    @action(detail=False, methods=['post'], url_path='delete_todo')
    def delete_todo(self, request):
        try:
            todo_id = request.data.get('id')
            if not todo_id:
                return Response({
                    'code': 400,
                    'message': '缺少待办事项ID'
                }, status=status.HTTP_400_BAD_REQUEST)

            todo = TodoList.objects.get(id=todo_id)
            todo.delete()
            return Response({
                'code': 200,
                'message': '删除成功'
            })
        except TodoList.DoesNotExist:
            return Response({
                'code': 404,
                'message': '待办事项不存在'
            }, status=status.HTTP_404_NOT_FOUND)
        except Exception as e:
            return Response({
                'code': 500,
                'message': f'删除失败: {str(e)}'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
